//
//  BHHomeChoseCityViewController.swift
//  BigHealth
//
//  Created by 蔺百好 on 2021/6/9.
//

import UIKit

class BHHomeChoseCityViewController: BHBaseViewController {

    lazy var locationView: BHHomeCityLocationView = {
        let view = BHHomeCityLocationView.loadFromXib()
        view.frame = CGRect(x: 0, y: UIScreen.begainY, width: UIScreen.width, height: 108)
        return view
    }()
    
    lazy var hotGroupView: BHHomeHotCityView = {
        let view = BHHomeHotCityView.loadFromXib()
        view.isHidden = true
        view.delegate = self
        return view
    }()
    
    lazy var provinceTable: UITableView = {
        let view = UITableView.buildTableView(style: .plain)
        view.register(UINib.init(nibName: "BHHomeChoseCityCell", bundle: nil), forCellReuseIdentifier: "BHHomeChoseCityCell")
        view.delegate = self
        view.dataSource = self
        return view
    }()
    
    lazy var cityTable: UITableView = {
        let view = UITableView.buildTableView(style: .plain)
        view.register(UINib.init(nibName: "BHHomeChoseCityCell", bundle: nil), forCellReuseIdentifier: "BHHomeChoseCityCell")
        view.delegate = self
        view.dataSource = self
        view.backgroundColor = .color_f8f8f8
        return view
    }()
    
    var choseCityActBlock:((String,String) -> Void)?
    
    deinit {
        NotificationCenter.default.removeObserver(self)
    }
    
    
    fileprivate var hotCityArray: [BHCommonDicModel] = []
    fileprivate var cityArray: [BHHomeCityModel] = []
    fileprivate var provinceIndex: Int = 0
    override func viewDidLoad() {
        super.viewDidLoad()

        self.bh_navigationBar.title_label.text = "选择城市"
        self.bh_navigationBar.backBtn.setImage(UIImage.init(named: "bh_com_vcClose_sign"), for: .normal)
        
        self.locationView.cityBtn.setTitle(" \(BHLocationManager.shared.cityName)", for: .normal)
        self.locationView.cityBtnWidth.constant = CGFloat((BHLocationManager.shared.cityName.count * 15)+45)
        self.view.addSubview(self.locationView)
        self.view.addSubview(self.hotGroupView)
        
        self.locationView.refresh_locationBtn.addBtnAction(action: { (_) in
            BHLocationManager.shared.requestLocation()
        }, for: .touchUpInside)
        
        self.view.addSubview(self.provinceTable)
        self.view.addSubview(self.cityTable)
        
        self.loadHotCityService()
        self.loadProvinceService()
        
        NotificationCenter.default.addObserver(self, selector: #selector(refreshCity), name: NSNotification.Name.init(String.refreshCityKey), object: nil)

    }
    
    @objc func refreshCity() {
        self.locationView.cityBtn.setTitle(" \(BHLocationManager.shared.cityName)", for: .normal)
        self.locationView.cityBtnWidth.constant = CGFloat((BHLocationManager.shared.cityName.count * 15)+45)
    }
    

}

extension BHHomeChoseCityViewController{
    func configCity() {
        self.hotGroupView.frame = CGRect(x: 0, y: 108+UIScreen.begainY+10, width: UIScreen.width, height: BHHomeHotCityView.hotHeight(count: self.hotCityArray.count))
        self.hotGroupView.isHidden = false
        self.hotGroupView.hotArray = self.hotCityArray
        
        self.view.backgroundColor = .color_f8f8f8
        
        let startY = self.hotGroupView.bh_bottom
        self.provinceTable.frame = CGRect(x: 0, y: startY, width: 100, height: UIScreen.height-startY)
        self.cityTable.frame = CGRect(x: 100, y: startY, width: UIScreen.width-100, height: UIScreen.height-startY)
    }
}

extension BHHomeChoseCityViewController: BHHomeHotCityViewDelegate {
    func didHotCityChose(model: BHCommonDicModel) {
        self.choseCityActBlock?(model.value,model.text)
        self.navigationController?.popViewController(animated: true)
    }
}

extension BHHomeChoseCityViewController: UITableViewDataSource {
   
    func numberOfSections(in tableView: UITableView) -> Int {
        return 1
    }
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        if tableView == self.provinceTable {
            return self.cityArray.count
        }else {
            if self.cityArray.count != 0 {
                let model: BHHomeCityModel = self.cityArray[self.provinceIndex]
                return model.childArray.count
            }
            return 0
        }
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "BHHomeChoseCityCell", for: indexPath) as! BHHomeChoseCityCell
        if tableView == provinceTable {
            let model: BHHomeCityModel = self.cityArray[indexPath.row]
            cell.text_label.text = model.name
            cell.canChose = true
            cell.chose = indexPath.row == self.provinceIndex
        }else {
            let provinceModel: BHHomeCityModel = self.cityArray[self.provinceIndex]
            let model: BHHomeCityModel = provinceModel.childArray[indexPath.row]
            cell.text_label.text = model.name
            cell.canChose = false
        }
        return cell
    }
}

extension BHHomeChoseCityViewController: UITableViewDelegate {
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        return 40
    }
    
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        if tableView == self.provinceTable {
            let model: BHHomeCityModel = self.cityArray[indexPath.row]
            if model.ifMducg == 1 { // 直辖市
                self.choseCityActBlock?(model.code,model.name)
                
                self.navigationController?.popViewController(animated: true)
            }else {
                self.provinceIndex = indexPath.row
                self.provinceTable.reloadData()
                if model.childArray.count != 0 {
                    self.cityTable.reloadData()
                }else {
                    self.loadCityService(model)
                }
            }
            
        }else {
            let provinceModel: BHHomeCityModel = self.cityArray[self.provinceIndex]
            let model: BHHomeCityModel = provinceModel.childArray[indexPath.row]
            self.choseCityActBlock?(model.code,model.name)
            self.navigationController?.popViewController(animated: true)
        }
    }
}

// MARK: 接口
extension BHHomeChoseCityViewController {
    func loadHotCityService() {
        let manager = BHHTTPClient.init()
        manager.get(url: String.common_get_dic_url+"hot_city", paramters: nil) { (success, errorMsg, responseObject)  in
            if success == true {
                let result = BHJsonTool.decodeArrayFromDic(dic: responseObject, key: "result")
                
                for dic in result {
                    let model: BHCommonDicModel = BHCommonDicModel.init()
                    model.parseDic(dic as! [String: Any])
                    self.hotCityArray.append(model)
                }
                
                self.configCity()
                
            }else {
                BHToast.toast(text: errorMsg)
              
            }
        }
    }
    
    func loadProvinceService()  {
        let manager = BHHTTPClient.init()
        manager.get(url: String.home_province_listUrl, paramters: nil) { (success, errorMsg, responseObject)  in
            if success == true {
                let result = BHJsonTool.decodeArrayFromDic(dic: responseObject, key: "result")
                
                for dic in result {
                    let model: BHHomeCityModel = BHHomeCityModel.init()
                    model.parseDic(dic as! [String: Any])
                    self.cityArray.append(model)
                }
                let model: BHHomeCityModel = BHHomeCityModel.init()
                model.code = "-1"
                model.parentCode = "-1"
                model.ifMducg = 0
                model.name = "全部"
                self.cityArray.insert(model, at: 0)
                
                self.provinceTable.reloadData()
                
            }else {
                BHToast.toast(text: errorMsg)
    
            }
        }
    }
    
    func loadCityService(_ model: BHHomeCityModel)  {
        let manager = BHHTTPClient.init()
        manager.get(url: String.home_city_listUrl, paramters: ["parentCode":model.code]) { (success, errorMsg, responseObject)  in
            if success == true {
                let result = BHJsonTool.decodeArrayFromDic(dic: responseObject, key: "result")
                
                for dic in result {
                    let childModel: BHHomeCityModel = BHHomeCityModel.init()
                    childModel.parseDic(dic as! [String: Any])
                    model.childArray.append(childModel)
                }
                self.cityTable.reloadData()
                
            }else {
                BHToast.toast(text: errorMsg) 
            }
        }
    }
}
